import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable, tap } from "rxjs";
import { map } from "rxjs/operators";
import { InjectRepository } from "@nestjs/typeorm";
import { Log } from "@/modules/log/entities/log.entity";
import { Repository } from "typeorm";
import { argumentsToString } from "@/common/utils/common";

@Injectable()
export class LogInterceptor implements NestInterceptor {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>
    ) {
    }
    
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // 在这里修改请求
        const request = context.switchToHttp().getRequest();
        // response.header("X-Response-Interceptor", "true");
        // console.log("request", request);
        return next.handle().pipe(
            tap(() => (this.logRepository.save({
                ip: request.ip,
                userFlag: request?.user?.username,
                name: decodeURIComponent(request.headers["api-name"]),
                method: request.method,
                arguments: argumentsToString(request), // (request.body || request.params || request.query),
                // message: exception.message,
                // status:request.status,
                path: request.originalUrl,
                type: 1
            })))
        );
    }
}